package cc.wsyw126.java.whatisjava.ThinkingInUnsafe;

import sun.misc.Unsafe;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.security.ProtectionDomain;

/**
 * Created by junpeng.yang on 16/12/28.
 */
public class DynamicClasses {
    private byte[] getClassContent() throws Exception {
        File f = new File("/Users/yangdp/Documents/workspace/GitWsyw126/java/target/classes/cc/wsyw126/java/whatisjava/ThinkingInUnsafe/DynamicClasses.class");
        FileInputStream input = new FileInputStream(f);
        byte[] content = new byte[(int) f.length()];
        input.read(content);
        input.close();
        return content;
    }

    public void invokeMethod() throws Exception {
        byte[] classContents = getClassContent();
//        Class c = getUnsafe().defineClass(null, classContents, 0, classContents.length, this.getClass().getClassLoader(), );
//        c.getMethod("a").invoke(c.newInstance(), null); // 1
    }

    public Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe) f.get(null);
        return unsafe;
    }

    public static void main(String[] args) throws Exception {
        DynamicClasses dynamicClasses = new DynamicClasses();
    }
}
